
/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.waveprotocol.wave.model.document.operation.algorithm.transformer {
import org.goverla.collections.ArrayList;
import org.goverla.collections.HashMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.AttributesUpdate;
import org.waveprotocol.wave.model.document.operation.impl.AttributesUpdateImpl;

final class UpdateAttributesCache extends RangeCache {
	
	private var update:AttributesUpdate;
	private var parent:Target;
	function UpdateAttributesCache(t:Target, update:AttributesUpdate) {
		this.update = update;
		this.parent = t;
	}
	
	
	override function resolveRetain(itemCount:int):void {
		parent.flushAnnotations();
		parent.targetDocument.updateAttributes(update);
		parent.otherTarget.targetDocument.retain(1);
	}
	
	
	override  function resolveDeleteElementStart(type:String, attributes:Attributes):void {
		parent.otherTarget.doDeleteElementStart(type, attributes.updateWith(update));
		++parent.otherTarget.depth;
	}
	
	
	override function resolveReplaceAttributes(oldAttributes:Attributes, newAttributes:Attributes):void {
		parent.flushAnnotations();
		parent.targetDocument.retain(1);
		parent.otherTarget.targetDocument.replaceAttributes(oldAttributes.updateWith(update),
			newAttributes);
	}
	
	
	override function resolveUpdateAttributes(update:AttributesUpdate):void {
		parent.flushAnnotations();
		var updated:HashMap= new HashMap();
		for (var i:int= 0; i < update.changeSize(); ++i) {
			updated.addItem(update.getChangeKey(i), update.getNewValue(i));
		}
		var newUpdate:AttributesUpdate= new AttributesUpdateImpl(null);
		// TODO: This is a little silly. We should do this a better way.
		for (var i:int= 0; i < this.update.changeSize(); ++i) {
			var key:String= this.update.getChangeKey(i);
			var newOldValue:String= String((updated.containsKey(key) ? updated.getItem(key)
				: this.update.getOldValue(i)));
			newUpdate = newUpdate.composeWith(AttributesUpdateImpl.of(key,
				newOldValue, this.update.getNewValue(i)));
		}
		parent.targetDocument.updateAttributes(newUpdate);
		var keySet:ArrayList= new ArrayList();
		for (var i:int= 0; i < this.update.changeSize(); ++i) {
			keySet.addItem(this.update.getChangeKey(i));
		}
		var transformedAttributes:AttributesUpdate= update.exclude(keySet);
		parent.otherTarget.targetDocument.updateAttributes(transformedAttributes);
	}
	
}
}